package com.cloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.cloud.Pay;
import com.cloud.R;
import com.cloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @BelongsProject: my
 * @BelongsPackage: com.cloud.controller
 * @Author: ji ge
 * @CreateTime: 2024-02-04  13:37
 * @Description: TODO
 * @Version: 1.0
 */
@RestController
@Slf4j
public class CircleBreakerController {
    public static final String SERVICE_URL ="http://nacos-payment-provider";
    @Resource
    private RestTemplate restTemplate;

    @Resource
    private PaymentService paymentService;
    @RequestMapping("/consumerFallback/{id}")
    @SentinelResource(value = "fallback",fallback = "handlerFallback",blockHandler = "blockHandler",exceptionsToIgnore = {IllegalArgumentException.class})
    //    @SentinelResource(value = "fallback") //没有配置
//    @SentinelResource(value = "fallback", fallback = "handlerFallback") //fallback只负责业务异常
//    @SentinelResource(value = "fallback",blockHandler = "blockHandler") //blockHandler只负责sentinel控制台配置违规
    public R<Pay> fallback(@PathVariable Long id){
        R<Pay> getForObject =restTemplate.getForObject(SERVICE_URL+"/paymentSQL/"+id,R.class,id);
        if (id == 4) {
            throw new IllegalArgumentException("IllegalArgumentException,非法参数异常....");
        } else if (getForObject.getData() == null) {
            throw new NullPointerException("NullPointerException,该ID没有对应记录,空指针异常");
        }

        return getForObject;

    }

    public R handlerFallback(@PathVariable Long id,Throwable throwable){
        Pay pay = new Pay(id, null);
        return new R(444,"兜底handler fallback 异常="+throwable.getMessage(),pay);
    }

    public R blockHandler(@PathVariable Long id, BlockException blockException){
        Pay pay = new Pay(id, null);
        return new R(444,"sentinel限流 fallback 异常="+blockException.getMessage(),pay);
    }

    @GetMapping("/consumer/paymentSQL/{id}")
    public R<Pay> paymentSQL(@PathVariable Long id){
        return paymentService.paymentSQL(id);
    }
}
